package com.xiebishe.mylibrary.net.retrofit.remoteCallAdapter

import com.alibaba.fastjson.util.ParameterizedTypeImpl
import com.xiebishe.mylibrary.net.retrofit.bean.NetBaseBean
import net.caiyixiu.liaoji.net.retrofit.remoteCallAdapter.CoroutineCall
import retrofit2.CallAdapter
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

class RemoteCallFactory : CallAdapter.Factory() {
    override fun get(returnType: Type, annotations: Array<out Annotation>?, retrofit: Retrofit?): CallAdapter<*, *>? {
        val rawType = getRawType(returnType)
        if (!CoroutineCall::class.java.isAssignableFrom(rawType)) {
            return null
        }
        if (returnType !is ParameterizedType) {
            throw  IllegalStateException(
                CoroutineCall::class.java.simpleName + " return type must be parameterized"
                    + " as " + CoroutineCall::class.java.simpleName + "<Foo> or " + CoroutineCall::class.java.simpleName + "<? extends Foo>")
        }
        val innerType = getParameterUpperBound(0, returnType)
        val rawType1 = getRawType(innerType)
        // 返回为 RemoteCall<RemoteData<...>>错误
        if (rawType1 == NetBaseBean::class.java) {
            throw  IllegalStateException(CoroutineCall::class.java.simpleName + " return type must not be" + NetBaseBean::class.java.simpleName)
        }
        val actualTypeArguments: Array<Type> = returnType.actualTypeArguments
        val newParameterizedTypeWithOwner = ParameterizedTypeImpl(actualTypeArguments, null, NetBaseBean::class.java)
        return RemoteCallAdapter(newParameterizedTypeWithOwner)
    }

    companion object {
        @JvmStatic
        fun create(): RemoteCallFactory {
            return RemoteCallFactory()
        }
    }
}